package db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MySQLiteHelper extends SQLiteOpenHelper {

	public static final String TABLE_RICETTA_INGREDIENTE = "ricettaToIngrediente";
	public static final String TABLE_RICETTA = "ricette";
	public static final String TABLE_INGREDIENTE = "ingredienti";
	public static final String COLUMN_CHIAVE = "_id";
	public static final String COLUMN_NOME = "nome";
	public static final String COLUMN_DESCRIZIONE = "descrizione";
	public static final String COLUMN_CATEGORIA = "categoria";
	public static final String COLUMN_IMMAGINE = "immagine";
	public static final String COLUMN_INGREDIENTE = "ingrediente";
	public static final String COLUMN_RICETTA = "ricetta";
	public static final String COLUMN_TEMPO = "tempo";

	private static final String DATABASE_NAME = "app.db";
	private static final int DATABASE_VERSION = 1;

	// Database creation sql statement
	private static final String FOREIGN_ENABLE = "PRAGMA foreign_keys = ON;";
	
	private static final String DATABASE_CREATE = "create table " +
			
			TABLE_INGREDIENTE + "(" + COLUMN_CHIAVE
			+ " integer primary key autoincrement, " + COLUMN_NOME
			+ " text not null," + COLUMN_IMMAGINE
			+ " blob," + COLUMN_CATEGORIA
			+ " text not null);"
			
			+ TABLE_RICETTA + "(" + COLUMN_CHIAVE
			+ " integer primary key autoincrement, " + COLUMN_NOME
			+ " text not null," + COLUMN_DESCRIZIONE
			+ " text not null," + COLUMN_IMMAGINE
			+ " text not null," + COLUMN_CATEGORIA
			+ " text not null," + COLUMN_TEMPO
			+ " integer)"
			
			+ TABLE_RICETTA_INGREDIENTE + "(" + COLUMN_INGREDIENTE
			+ " INTEGER REFERENCES INGREDIENTE( "+COLUMN_CHIAVE+" ),"
		    + COLUMN_RICETTA
			+ " INTEGER REFERENCES RICETTA( "+COLUMN_CHIAVE+" );"
		    ;

	private static final String DROPTABLE = "drop table if exists " + TABLE_INGREDIENTE;

	public MySQLiteHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onOpen(SQLiteDatabase database){
		database.execSQL(DROPTABLE);
		database.execSQL(DATABASE_CREATE);
	}
	
	@Override
	public void onCreate(SQLiteDatabase database) {
		database.execSQL(FOREIGN_ENABLE);
		database.execSQL(DATABASE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		/*Log.w(MySQLiteHelper.class.getName(),
				"Upgrading database from version " + oldVersion + " to "
						+ newVersion + ", which will destroy all old data");
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
		onCreate(db);*/
	}

} 